package com.antler.mobilesniffer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsMessage;

import com.antler.utils.MyLog;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SMSReceiver extends BroadcastReceiver {
    protected static final String TAG = "[ANTLER]" + SMSReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        MyLog.log(TAG, "onReceive: " + intent);

        Bundle bundle = intent.getExtras();
        String format = intent.getStringExtra("format");

        SmsMessage msg;
        if (null != bundle) {
            Object[] smsObj = (Object[]) bundle.get("pdus");
            if (null != smsObj) {
                String receiveTime = "";
                String strOriginatingAddress = "";
                StringBuffer strDisplayMessageBody = new StringBuffer(256);

                for (Object obj : smsObj) {
                    if (Build.VERSION.SDK_INT < 23) {
                        msg = SmsMessage.createFromPdu((byte[]) obj);
                    } else {
                        msg = SmsMessage.createFromPdu((byte[]) obj, format);
                    }

                    if (receiveTime.isEmpty()) {
                        Date date = new Date(msg.getTimestampMillis());
                        SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        receiveTime = dataFormat.format(date);
                    }

                    if (strOriginatingAddress.isEmpty()) {
                        strOriginatingAddress = msg.getOriginatingAddress();
                    }

                    strDisplayMessageBody.append(msg.getDisplayMessageBody());
                }

                MyLog.log(TAG, String.format("time:%s, number:%s, body:%s", receiveTime, strOriginatingAddress, strDisplayMessageBody.toString()));

                Intent intentSMSMsg = new Intent(context, MainService.class);
                intentSMSMsg.setAction(MainService.ACTION_FORWARD_SMS);
                intentSMSMsg.putExtra(MainService.SMS_RECEIVE_TIME, receiveTime);
                intentSMSMsg.putExtra(MainService.SMS_NUMBER, strOriginatingAddress);
                intentSMSMsg.putExtra(MainService.SMS_BODY, strDisplayMessageBody.toString());
                context.startService(intentSMSMsg);
            }
        }
    }
}
